/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Friend;
import edu.cmu.fithub.db.bean.Group;
import edu.cmu.fithub.db.bean.GroupMembers;
import edu.cmu.fithub.db.bean.User;

public class JoinGroupAction extends Action {

	public JoinGroupAction() {
	}

	public String getName() {
		return "joinGroup.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {
			GroupMembers groupMembers = new GroupMembers();
			User user = (User) request.getSession().getAttribute("user");
			String groupId = request.getParameter("groupId");

			Session dbSession = DBHelper.getSessionFactory().openSession();
			List<Group> groupList = dbSession
					.createCriteria(Group.class)
					.add(Restrictions.eq("groupId", (Integer.parseInt(groupId))))
					.list();
			groupMembers.setGroup(groupList.get(0));
			groupMembers.setUserId(user.getUserId());
			groupMembers.setUserName(user.getFirstName());
			dbSession.beginTransaction();
			dbSession.save(groupMembers);
			dbSession.getTransaction().commit();
		} catch (NumberFormatException e) {
			// TODO error handling
			e.printStackTrace();
			return "error.jsp";
		}

		return "redirectToHome.jsp";
	}
}
